/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年12月27日         cassie
 */

package com.coocaa.launcher.pattern.normal.hotseat;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;

import com.coocaa.launcher.framework.launcherhost.view.AppItemView;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.APP_ITEM_TYPE;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.AppEntryData;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.AppItemData;
import com.coocaa.launcher.pattern.normal.NormalController.HotSeatExecutor;
import com.coocaa.launcher.pattern.normal.UIConfig;
import com.coocaa.launcher.pattern.normal.item.AppBaseItemView;
import com.coocaa.launcher.pattern.normal.item.TempAddView;
import com.coocaa.launcher.pattern.normal.pick.PickActivity;
import com.coocaa.launcher.pattern.normal.pick.PickResultListener;
import com.coocaa.launcher.util.PathConstants;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;

public class HotSeatLine extends FrameLayout {
    private Context mContext;
    private int lineIndex;
    // private ANIM animType;
    // private static int destHeight = UIConfig.hotSeatLineHeight;
    // private static int step = destHeight / 12;
    private int appItemCount = 0;
    private ChildFocusListener parentFocusListener;
    private ChildClickListener parentClickListener;
    private HotSeatExecutor hotSeatExecutor; // 用来处理remove的action
    // private LineShrinkListener lineShrinkListener;
    private PickResultListener pickResultListener;

    private boolean inEditState = false;

    public enum ANIM {
        NONE, EXPAND, SHRINK
    }

    ;

    public HotSeatLine(Context context, int lineIndex, ChildFocusListener listener) {
        super(context);
        // TODO Auto-generated constructor stub
        this.mContext = context;
        this.lineIndex = lineIndex;
        this.parentFocusListener = listener;
        this.setClickable(false);
        this.setFocusableInTouchMode(false);
        for (int i = 0; i < UIConfig.HotSeatItemCountPerPage; i++) {
            TempAddView addView = new TempAddView(context);
            addOrReplaceView(addView, i);
        }
    }

    public void addOrReplaceView(AppItemView item, int pos) {
        int realIndex = pos + lineIndex * UIConfig.HotSeatItemCountPerPage;
        AppItemView oldPosView = (AppItemView) this.findViewById(realIndex);
        if (oldPosView != null)
            this.removeView(oldPosView);
        item.setId(realIndex);
        item.setOnFocusChangeListener(childFocusListener);
        item.setOnKeyListener(childKeyListener);
        this.addView(item);

        if (!item.getViewType().equals(TempAddView.viewType)) {
            if (oldPosView.getViewType().equals(TempAddView.viewType))
                appItemCount++;
            LayoutParams params = new LayoutParams(UIConfig.hotSeatItemWidth,
                    UIConfig.appItemHeight, Gravity.TOP);
            params.leftMargin = pos * (UIConfig.hotSeatItemWidth + UIConfig.hotSeatItemSpacing);
            params.topMargin = UIConfig.hotSeatTopPadding;
            ((AppBaseItemView) item).setEditState(inEditState);
            item.setLayoutParams(params);
            item.setOnClickListener(appClickListener);
        } else {
            if (oldPosView != null && !(oldPosView.getViewType().equals(TempAddView.viewType)))
                appItemCount--;
            LayoutParams params = new LayoutParams(UIConfig.hotSeatItemWidth,
                    UIConfig.tempAddItemHeight, Gravity.TOP);
            params.leftMargin = pos * (UIConfig.hotSeatItemWidth + UIConfig.hotSeatItemSpacing);
            params.topMargin = UIConfig.hotSeatTopPadding;
            item.setLayoutParams(params);
            item.setOnClickListener(addClickListener);
            if (inEditState) {
                item.setAlpha(1.0f);
                item.setVisibility(View.VISIBLE);
            }
        }
    }

    public void enterEditState(int duration) {
        inEditState = true;
        setChildrenFocusable(true);
        for (int i = 0; i < this.getChildCount(); i++) {
            AppItemView v = (AppItemView) this.getChildAt(i);
            v.setFocusable(true);
            if (v.getViewType().equals(TempAddView.viewType))
                ((TempAddView) v).show(duration);
            else {
                AppBaseItemView appItem = (AppBaseItemView) v;
                appItem.setEditState(true);
            }
        }
        // expand();
    }

    public void exitEditState(int duration) {
        for (int i = 0; i < this.getChildCount(); i++) {
            AppItemView v = (AppItemView) this.getChildAt(i);
            if (v.getViewType().equals(TempAddView.viewType))
                ((TempAddView) v).hide(duration);
            else {
                AppBaseItemView appItem = (AppBaseItemView) v;
                appItem.setEditState(false);
            }
        }
        inEditState = false;
    }

    public int getLineIndex() {
        return this.lineIndex;
    }

    public int getAppItemCount() {
        return this.appItemCount;
    }

    public void setChildrenFocusable(boolean focusable) {
        if (inEditState) {
            for (int i = 0; i < getChildCount(); i++) {
                getChildAt(i).setFocusable(focusable);
            }
        } else {
            for (int i = 0; i < getChildCount(); i++) {
                AppItemView v = (AppItemView) this.getChildAt(i);
                if (v.getViewType().equals(TempAddView.viewType))
                    v.setFocusable(false);
                else
                    v.setFocusable(focusable);
            }
        }
    }

    // 找到第一个可以添加应用的位置
    public int getFirstAvailablePos() {
        if (getAppItemCount() >= UIConfig.HotSeatItemCountPerPage)
            return -1;
        for (int i = 0; i < UIConfig.HotSeatItemCountPerPage; i++) {
            int id = i + lineIndex * UIConfig.HotSeatItemCountPerPage;
            AppItemView view = (AppItemView) this.findViewById(id);
            if (view.getViewType().equals(TempAddView.viewType)) {
                return id;
            }
        }
        return -1;
    }

    public void setChildFocusPos(int pos) {
        int childId = pos + lineIndex * UIConfig.HotSeatItemCountPerPage;
        AppItemView v = (AppItemView) this.findViewById(childId);
        if (v == null)
            return;
        if (inEditState) // 如果在编辑状态，此pos的item可获取焦点
        {
            v.requestFocus();
            return;
        }
        // 否则，则只有非TempAppView的item可获取焦点
        if (!(v.getViewType().equals(TempAddView.viewType))) {
            v.requestFocus();
            return;
        }
        boolean found = false;
        for (int i = 1; i < this.getChildCount() && !found; i++) {
            AppItemView item;
            if (childId - i >= lineIndex * UIConfig.HotSeatItemCountPerPage) {
                item = (AppItemView) this.findViewById(childId - i);
                if (!(item.getViewType().equals(TempAddView.viewType))) {
                    item.requestFocus();
                    break;
                }
            }
            if (childId + i < (lineIndex + 1) * UIConfig.HotSeatItemCountPerPage) {
                item = (AppItemView) this.findViewById(childId + i);
                if (!(item.getViewType().equals(TempAddView.viewType))) {
                    item.requestFocus();
                    break;
                }
            }
        }
    }

    private OnFocusChangeListener childFocusListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            // TODO Auto-generated method stub
            if (hasFocus) {
                if (parentFocusListener != null) {
                    if (v.getWidth() <= 0 || v.getHeight() <= 0) {
                        int index = v.getId() % UIConfig.HotSeatItemCountPerPage;
                        int left = index
                                * (UIConfig.hotSeatItemWidth + UIConfig.hotSeatItemSpacing)
                                + UIConfig.hotSeatLeftSpacing;
                        int top = UIConfig.hotSeatTopPadding;
                        int right = left + v.getLayoutParams().width;
                        int bottom = top + v.getLayoutParams().height;
                        if (inEditState) {
                            top += lineIndex * UIConfig.hotSeatLineHeight;
                            bottom += lineIndex * UIConfig.hotSeatLineHeight;
                        }
                        parentFocusListener.onChildFocusChange(new Rect(left, top, right, bottom));
                        return;
                    }
                    if (inEditState) {
                        int left = getLeft() + v.getLeft();
                        int top = getTop() + v.getTop();
                        int right = getLeft() + v.getRight();
                        int bottom = getTop() + v.getBottom();
                        parentFocusListener.onChildFocusChange(new Rect(left, top, right, bottom));
                    } else {
                        int left = getLeft() + v.getLeft();
                        int top = v.getTop();
                        int right = getLeft() + v.getRight();
                        int bottom = v.getBottom();
                        parentFocusListener.onChildFocusChange(new Rect(left, top, right, bottom));
                    }
                }
            }
            AppItemView view = (AppItemView) v;
            if (!inEditState && !view.getViewType().equals(TempAddView.viewType)) {
                AppBaseItemView appItem = (AppBaseItemView) view;
                appItem.setTitleMarquee(hasFocus);
            }
        }
    };

    // public static boolean handleKey = true;
    // public static void enableKey()
    // {
    // handleKey = true;
    // }
    //
    // public static void disableKey()
    // {
    // handleKey = false;
    // }

    private OnKeyListener childKeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (!HotSeatView.handleItemKey)
                LogUtils.d("key", "hotseat item onkey, keycode = " + keyCode
                        + ", handleItemKey = false");
            return !HotSeatView.handleItemKey;
        }
    };

    public void setChildClickListener(ChildClickListener listener) {
        this.parentClickListener = listener;
    }

    public void setHotSeatExecutor(HotSeatExecutor executor) {
        this.hotSeatExecutor = executor;
    }

    // public void setShrinkListener(LineShrinkListener listener)
    // {
    // this.lineShrinkListener = listener;
    // }

    public void setPickResultListener(PickResultListener listener) {
        this.pickResultListener = listener;
    }

    private OnClickListener addClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (parentClickListener != null)
                parentClickListener.onChildClicked(v.getId());
            Intent i = new Intent(mContext, PickActivity.class);
            // i.putExtra("listener", pickResultListener);
            PickActivity.setPickResultListener(pickResultListener);
            ((Activity) mContext).startActivity(i);// ForResult(i, 0);
        }
    };

    private OnClickListener appClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            AppItemData data = ((AppItemView) v).getData();
            if (data == null)
                return;
            if (inEditState) {
                if (parentClickListener != null)
                    parentClickListener.onChildClicked(v.getId());
                if (hotSeatExecutor != null) {
                    APP_ITEM_TYPE dataType = APP_ITEM_TYPE.valueOf(data.getType());
                    switch (dataType) {
                        case APP_ENTRY_TYPE:
                            hotSeatExecutor.sendRemoveEntryAction((AppEntryData) data);
                            break;
                        case APP_FOLDER_TYPE:
                            break;
                        case APP_WIDGET_TYPE:
                            break;
                        case APP_SHORTCUT_TYPE:
                            break;
                        default:
                            break;
                    }
                }
            } else {
                String packageName = ((AppEntryData) data).getPackageName();
                String activityName = ((AppEntryData) data).getActivityName();
                try {
                    XServiceManager.getLitePMService().startAppByComponentName(mContext.getClass().getName(), false,
                            new ComponentName(packageName, activityName));
                    submitLogLaunchApp(v.getId(), data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // Intent intent = null;
                // if (activityName != null && !activityName.equals(""))
                // {
                // intent = new Intent();
                // intent.setClassName(packageName, activityName);
                // } else
                // intent = mContext.getPackageManager().getLaunchIntentForPackage(packageName);
                // Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(
                // ((AppEntryData) info).getPackageName());
                // if (intent == null)
                // return;
                // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // mContext.startActivity(intent);
                // Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(
                // ((AppEntryData)data).getPackageName());
                // if (intent == null)
                // return;
                // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // mContext.startActivity(intent);
            }
        }
    };

    private void submitLogLaunchApp(int id, AppItemData data) {
        int row = id / UIConfig.HotSeatItemCountPerPage;
        int column = id % UIConfig.HotSeatItemCountPerPage;
        int appId = -1;
        try {
            appId = Integer.parseInt(data.getId());
        } catch (Exception e) {
        }
        String appName = data.getTitle();
        String pkgName = data.getPackageName();
        LogAPIForAppStore.shortcutsOpen(row, column, appId, pkgName, appName);
        LogAPIForAppStore.appStartPath(PathConstants.LaunchAppPath.HOT_SEAT.toString(), appId,
                pkgName, appName);

        // 提交启动应用圈的路径
        if (pkgName.equals(mContext.getPackageName()))
            LogAPIForAppStore.appStoreStartPath(PathConstants.LaunchAppStorePath.HOT_SEAT
                    .toString());
    }
}
